/**
 * Copyright (c) @2015,重庆云途交通科技有限公司.版权所有
 */
package com.cqfae.deploycentral.app.config;

import java.io.IOException;

import javax.sql.DataSource;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.web.bind.annotation.InitBinder;

import com.alibaba.druid.pool.DruidDataSource;

/**
 * Mybatis配置
 * 
 * @author yangheng940
 * @since 1.0.0
 */
@Configuration
public class MybatisConfig {

  // 注入配置
  @Autowired
  private DataSourceInfo dataSourceInfo;

  @Bean
  @InitBinder
  public DataSource dataSource() {
    DruidDataSource ds = new DruidDataSource();
    ds.setUrl(dataSourceInfo.getUrl());
    ds.setUsername(dataSourceInfo.getUsername());
    ds.setPassword(dataSourceInfo.getPassword());
    ds.setInitialSize(dataSourceInfo.getInitConnSize());
    ds.setMinIdle(dataSourceInfo.getMinIdleConnSize());
    ds.setMaxActive(dataSourceInfo.getMaxActiveConnSize());
    ds.setTimeBetweenEvictionRunsMillis(60000);
    ds.setDriverClassName(dataSourceInfo.getDriver());
    ds.setMaxWait(60000);
    ds.setMinEvictableIdleTimeMillis(300000);
    ds.setTestOnBorrow(false);
    ds.setTestOnReturn(false);
    ds.setTestWhileIdle(true);
    ds.setValidationQuery("SELECT 'x'");
    ds.setPoolPreparedStatements(false);
    return ds;
  }

  // spring 事务
  @Bean(name = "txManager")
  public DataSourceTransactionManager dataSourceTransactionManager() {
    DataSourceTransactionManager txManager = new DataSourceTransactionManager();
    txManager.setDataSource(dataSource());
    return txManager;
  }

  @Bean
  public SqlSessionFactoryBean sqlSessionFactoryBean() throws IOException {
    SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
    sqlSessionFactoryBean.setDataSource(dataSource());
    sqlSessionFactoryBean.setConfigLocation(new ClassPathResource(
        "/config/mybatis/mybatis-config.xml"));
    Resource[] mapperResources =
        new PathMatchingResourcePatternResolver()
            .getResources("classpath*:/config/mybatis/mapper/*.xml");
    sqlSessionFactoryBean.setMapperLocations(mapperResources);
    return sqlSessionFactoryBean;
  }
}
